﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Stitch.Database;

namespace Data.GameData.Entities
{
    public class EPopulation : EBaseObject
    {
        public static EPopulation LoadFromDB(Guid id)
        {
            string sqlStatement = "Select * from Population where id = '" + id.ToString() + "'";
            RunSQL(sqlStatement);

            DBRow dbRow = databaseResult.FetchArray();

            if (!databaseResult.MsSqlReader.HasRows)
                throw new Exception("No selected rows");
            if (databaseResult.MsSqlReader.FieldCount > 1)
                throw new Exception("Too many rows");

            EPopulation newObject = new EPopulation();
            newObject.values = dbRow;

            return newObject;
        }

        internal static List<EPopulation> GetAllForGame(Guid id)
        {
            string sqlStatement = "Select * from Population WHERE gameId = '" + id.ToString() + "'";
            RunSQL(sqlStatement);

            List<EPopulation> eEntities = new List<EPopulation>();

            DBRow dbRow = databaseResult.FetchArray();

            while (dbRow != null)
            {
                EPopulation newObject = new EPopulation();
                newObject.values = dbRow;
                eEntities.Add(newObject);

                dbRow = databaseResult.FetchArray();
            }

            return eEntities;
        }

        internal void Delete()
        {
            string sqlStatement = "DELETE FROM Population WHERE id = '" + values["id"].ToString() + "'";
            RunNonSelectSQL(sqlStatement);
        }

        internal void SaveToDB(bool isNew)
        {
            string sqlStatement;

            if (isNew)
            {
                sqlStatement = "INSERT INTO Population ("
                    + "id, gameId, size, iu, ownerId, populationLinkId"
                    + ") VALUES ("
                    + "'" + values["id"] + "', "
                    + "'" + values["gameId"] + "', "
                    + values["size"] + ", "
                    + values["iu"] + ", "
                    + "'" + values["ownerId"] + "', "
                    + "'" + values["populationLinkId"] + "')";
            }
            else
            {
                sqlStatement = "UPDATE Population SET "
                    + "'" + values["id"] + "', "
                    + "'" + values["gameId"] + "', "
                    + values["size"] + ", "
                    + values["iu"] + ", "
                    + "'" + values["ownerId"] + "', "
                    + "'" + values["populationLinkId"] + "' "
                    + "WHERE id = '" + values["id"] + "'";
            }

            RunNonSelectSQL(sqlStatement);
        }
    }
}
